package com.springboot.core.security.permission;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.springboot.system.domain.auth.UserInfo;
import com.springboot.common.exception.NotPermissionException;
import com.springboot.common.utils.HttpUtils;
import com.springboot.core.AuthUserHolder;
import com.springboot.core.log.LoggerUtil;
import com.springboot.core.web.spring.SpringMVCUtil;

/**
 * 权限验证aop
 * 
 * @ClassName: CheckPermissionAspect
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author 252956
 * @date 2019年10月21日 下午4:54:07
 *
 */
@Order(2)
@Aspect
@Component
public class CheckPermissionAspect {

	/**
	 * 定义拦截规则：拦截com.springboot包下面的所有类中，有@CheckPermission注解的方法 。
	 */
	@Around("@annotation(checkPermission)")
	public Object method(ProceedingJoinPoint pjp, CheckPermission checkPermission) throws Throwable {

		HttpServletRequest request = SpringMVCUtil.getRequest();
		String ip = HttpUtils.getIpAddr(request);
		String url = request.getRequestURI();

		UserInfo userInfo = AuthUserHolder.getUserInfo();
		List<String> permissionCodeList = userInfo.getPermissionCodeList();

		if (permissionCodeList == null || permissionCodeList.isEmpty()) {
			LoggerUtil.warn("用户[" + userInfo.getName() + "]未分配任何权限");
			throw new NotPermissionException("用户[" + userInfo.getName() + "]未分配任何权限");
		}

		boolean hasPermission = false;
		for (String e : permissionCodeList) {
			if (checkPermission.value().equals(e)) {
				hasPermission = true;
				break;
			}
		}
		if (!hasPermission) {
			LoggerUtil.warn("用户[" + userInfo.getName() + "]IP[" + ip + "]访问地址[" + url + "]无权限");
			throw new NotPermissionException("用户[" + userInfo.getName() + "]IP[" + ip + "]访问地址[" + url + "]无权限");

		}

		return pjp.proceed();
	}

}
